package check;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JdbcUtil {


    static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
    static final String DB_URL = "jdbc:mariadb://localhost:3306/drds_home";
    static final String USER = "root";
    static final String PASS = "root";


    public static Connection getConnection() {
        try {
            Class.forName(JDBC_DRIVER);
            Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);
            return connection;
        } catch (Exception e) {

            throw new RuntimeException("get connection error!", e);
        }

    }

    public static void close(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    public static List<Map<String, Object>> get(Connection connection, String sql, List<?> objectList)
            throws SQLException {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        int index = 1;
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (objectList != null && !objectList.isEmpty()) {
            for (int i = 0; i < objectList.size(); i++) {
                preparedStatement.setObject(index++, objectList.get(i));
            }
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        //
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        String[] columnLabels = new String[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            columnLabels[i - 1] = resultSetMetaData.getColumnLabel(i);
        }
        while (resultSet.next()) {
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 0; i < columnCount; i++) {
                Object object = resultSet.getObject(columnLabels[i]);
                map.put(columnLabels[i].toLowerCase(), object);
            }
            mapList.add(map);
        }
        close(resultSet, preparedStatement, null);
        return mapList;
    }

}  